package com.lancoo.answer.ui.ques.quesBody;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.lancoo.answer.R;
import com.lancoo.answer.component.InteractWebView;
import com.lancoo.answer.model.AnswerConstant;
import com.lancoo.answer.model.ConstantBean;
import com.lancoo.answer.model.TaskState;
import com.lancoo.answer.model.bean.Child;
import com.lancoo.answer.model.bean.ImportKlg;
import com.lancoo.answer.model.bean.Item;
import com.lancoo.answer.model.bean.Ques;
import com.lancoo.answer.model.bean.Type;
import com.lancoo.answer.ui.ques.SpliteLayoutFragment;
import com.lancoo.answer.util.DensityUtils;
import com.lancoo.answer.util.ExamFontSizeAdjustUtils;
import com.lancoo.answer.util.paperUtils.FragmentCommunicationUtils;

import org.jetbrains.annotations.NotNull;

import java.util.List;

/**
 * Created by pengmi on 2021/12/16 9:30
 * Description:题干高亮标记处理fragment
 */
public class HightLightQuseBodyFragment extends Fragment {

    private static final String TAG = "HightLightQus";

    private FrameLayout frameLayout;
    private InteractWebView interactWebView;
    private Ques ques;
    private String currentItemSortIndex = "";

    public static Fragment loadQueseFragment(int kindIndex, int queseIndex, int childIndex, int defaultIndex) {
        HightLightQuseBodyFragment queseFragment = new HightLightQuseBodyFragment();
        Bundle mBundle = new Bundle();
        mBundle.putInt(AnswerConstant.KEY_TYPEINDEX, kindIndex);
        mBundle.putInt(AnswerConstant.KEY_QUESINDEX, queseIndex);
        mBundle.putInt(AnswerConstant.KEY_CHILDINDEX, childIndex);
        mBundle.putInt(AnswerConstant.KEY_LOADCHILDINDEX, defaultIndex);
        queseFragment.setArguments(mBundle);
        return queseFragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.ev_fragment_ques_body, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (getArguments() == null || getContext() == null || getActivity() == null) {
            return;
        }
        List<Type> kindBeanListk = ConstantBean.Companion.getConstantExamBean().getTypeList();
        if (kindBeanListk == null) {
            return;
        }
        int typeIndex = getArguments().getInt(AnswerConstant.KEY_TYPEINDEX);
        int quesIndex = getArguments().getInt(AnswerConstant.KEY_QUESINDEX);
        int childIndex = getArguments().getInt(AnswerConstant.KEY_CHILDINDEX);
        if (kindBeanListk.get(typeIndex) == null ||
                kindBeanListk.get(typeIndex).getQuesList() == null) {
            return;
        }

        ques = kindBeanListk.get(typeIndex).getQuesList().get(quesIndex);
        interactWebView = new InteractWebView(getContext());
        interactWebView.setPadding(0, 0, 0, DensityUtils.dip2px(20f, getContext()));
        if (ques == null || ques.getQuesBody() == null) {
            return;
        }
        frameLayout = view.findViewById(R.id.framelayout);
        frameLayout.addView(interactWebView);
//        frameLayout.addView(webView);
        Log.e(TAG, "onViewCreated loadWebView");
        String quesBody = ques.getQuesBody();//大题题干
        Boolean isIndentation = ques.getIsIndentQuesBody();
        if (TextUtils.isEmpty(quesBody)) {//为空，取小题题干
            if (ques.getChildList() != null && ques.getChildList().size() > 0) {
                if (childIndex < ques.getChildList().size()) {
                    quesBody = ques.getChildList().get(childIndex).getChildAsk();
                    isIndentation = ques.getChildList().get(childIndex).getIsIndentChildAsk();
                } else {
                    quesBody = ques.getChildList().get(0).getChildAsk();
                    isIndentation = ques.getChildList().get(0).getIsIndentChildAsk();
                }
            }
        }
        if (quesBody == null) {
            quesBody = "";
        }
        StringBuilder sb_name = new StringBuilder();
        final StringBuilder sb_code = new StringBuilder();
        List<ImportKlg> importKlgList = ques.getImportKlgList();
        int index=0;
        if (importKlgList != null) {
            for (ImportKlg importKlg : importKlgList) {
//                if(index>10){
//                    continue;
//                }
                if (!TextUtils.isEmpty(importKlg.getUniqueCode())) {
                    if (!TextUtils.isEmpty(sb_name.toString())) {
                        sb_name.append("|");
                        sb_code.append("|");
                    }
                    sb_name.append(importKlg.getName());
                    if(TextUtils.isEmpty(importKlg.getCode())){
                        sb_code.append(importKlg.getUniqueCode());
                    }else{
                        sb_code.append(importKlg.getCode());
                    }
                }
                index++;
            }
        }
        Log.e("clickKlg","code点击知识点："+sb_code.toString());
        Log.e("clickKlg","name点击知识点："+sb_name.toString());
        interactWebView.setKlg(true);
        final String names = sb_name.toString().replace("'", "\\'")
                .replace("/", "\\/").replace(".", "\\.")
                .replace("(","\\(").replace(")","\\)");

        interactWebView.setQues(ques);
        interactWebView.setIsIndentation(isIndentation);
        interactWebView.initWebView(getActivity(), quesBody, new InteractWebView.Callback() {
            @Override
            public void clickCallback(@NotNull String position) {
                Log.e(TAG, "clickCallback position:" + position);
                if (ConstantBean.getTaskState() != TaskState.TRAINING) {
                    wvLoadUrl(position);
                    getRealIndex(position);
                }
            }

            @Override
            public void finishCallback() {
                initLayout();
                interactWebView.loadHighKLg("javascript:InitPageData('" + names + "','" + sb_code.toString() + "')");
            }
        });

    }

    private void wvLoadUrl(String position) {
        if (TextUtils.equals(currentItemSortIndex, position)) {
            return;
        }
        if (interactWebView == null) {
            return;
        }
        currentItemSortIndex = position;
        Log.e(TAG, "wvLoadUrl:" + position);
        interactWebView.scrollPosition(position);
        for (Child it : ques.getChildList()) {
            interactWebView.loadUrl(it.getItemList().get(0),
                    position.equals(it.getItemList().get(0).getItemSortIndex()),
                    false,
                    true);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (interactWebView != null) {
            interactWebView.release();
        }
        if (frameLayout != null) {
            frameLayout.removeAllViews();
        }
    }

    public void loadItemIndex(int childIndex) {

        if (ConstantBean.getTaskState() != TaskState.TRAINING &&
                ques != null && ques.getChildList() != null && ques.getChildList().size() > 0) {
            List<Child> childList = ques.getChildList();
            if (childIndex < childList.size() && childIndex >= 0) {
                if (childList.get(childIndex).getItemList() != null &&
                        childList.get(childIndex).getItemList().size() > 0) {

                    wvLoadUrl(childList.get(childIndex).getItemList().get(0).getItemSortIndex());
                }
            }

        }
    }

    private void getRealIndex(String position) {

        if (ques == null || ques.getChildList() == null) {
            return;
        }
        int childIndex = 0;
        for (Child child : ques.getChildList()) {
            List<Item> itemList = child.getItemList();
            if (itemList == null) {
                continue;
            }
            if (TextUtils.equals(position, itemList.get(0).getItemSortIndex())) {
                break;
            }
            childIndex++;
        }
        Log.e(TAG, "getRealIndex" + childIndex);
        FragmentCommunicationUtils.dealWithQuesBodyInteraction(this, childIndex);
    }


    public void adjustFontSize(){
        if(interactWebView!=null){
            interactWebView.setFontSize();
        }
    }

    public void initLayout() {
        Fragment parentFragment = getParentFragment();
        if (parentFragment instanceof SpliteLayoutFragment) {
            ((SpliteLayoutFragment) parentFragment).initLayout();
        }
    }
}